<template>
  <el-dialog
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    :visible="visible"
    width="40%"
    :close-on-click-modal="false"
    @close="close"
    @open="open"
  >
    <!-- 树形组件 -->
    <el-tree
      ref="treeRef"
      :data="permissionList"
      :default-expand-all="true"
      :props="defaultProps"
      node-key="id"
      show-checkbox
      check-strictly
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPermissionList, getRoleDetail, permissionsToRoles } from '@/api'
import transTree from '@/utils/transTree'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 权限点列表 （经过 transTree 方法处理之后）
      permissionList: [],
      // 树形组件配置选项
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeData: {
        id: '',
        permIds: []
      },
      // 当前角色已有的权限数组
      rolePermissions: []
    }
  },
  methods: {
    // 弹窗关闭之后触发
    close() {
      this.$emit('assignClose')
    },
    // 弹窗打开之后触发
    open() {
      this.getAllPermissionList()
    },
    // 获取所有权限点
    async getAllPermissionList() {
      const { data } = await getPermissionList()
      console.log(data)
      this.permissionList = transTree(data)
      this.permIds = this.$refs.treeRef.getCheckedKeys()
      // 在获取权限点列表之后，获取该角色已有的权限点
      const roleDetail = await getRoleDetail(this.id)
      this.rolePermissions = roleDetail.data.permIds
      this.$refs.treeRef.setCheckedKeys(this.rolePermissions)
    },
    // 确定按钮（提交）
    async submit() {
      await permissionsToRoles({
        id: this.id,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      // 提示用户
      this.$message.success('分配权限成功')
      this.close()
    }
  }
}
</script>

<style>

</style>
